/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable prettier/prettier */
/* eslint-disable @typescript-eslint/no-unused-vars */

// 按照特定的目录建立分类或者添加分类下数据
// eg： avatar/分类/xx.png
// eg： pic/分类/模板名/xx.png

// ######### 头像 #######
// 1、遍历完对应的目录
// 2、查询或者保存目录名，得到 categoryId，建立缓存map减少查库
// 3、创建模板，得到templateId，得到 一个 文件
// 4、创建文件记录
// #######################
// ######### 艺术照模板 #######
// 1、遍历完对应的目录
// 2、查询或者保存目录名，得到 categoryId，建立缓存map减少查库
// 3、创建模板，得到templateId，得到list文件
// 4、创建文件记录

const fs = require('fs');
const axios = require('axios');
const ProgressBar = require('progress');
const Path = require('path');
const FormData = require('form-data');
const { async } = require('rxjs');

const authorization =
  'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ3ZWl4aW5fb3BlbklkIjoib3cwdEk1VWVtN18wODNOYXZQQlBIR0RBQXlUZyIsImlwIjoiMTIwLjIyNy4zNy4xMTEiLCJ1c2VySWQiOiI2YmJkOWM4Yi0yMTA4LTQzODAtOTM0My0yODk2OWQyMTU3ZmMiLCJpYXQiOjE2OTk0NTE1NjMsImV4cCI6MTcwMjA0MzU2M30.5QoR33C-xfxlobmr4fE5Q26B7pIwTnLcbv1B1xjdyjw';
// js去实现表单查询，创建模板，上传文件，生成对应记录

// 调三个接口即可
// 1 遍历对应目录
let m = 0;
let dirMap = {};
let categoryMap = {};

async function getFilesForAvatar(dir) {
  const fileDirs = fs.readdirSync(dir);
  for (let i = 0; i < fileDirs?.length; i++) {
    const tempFile = Path.join(dir, fileDirs[i]);
    const fileStat = fs.statSync(tempFile);
    if (fileStat.isFile()) {
      if (fileDirs[i] === '.DS_Store') {
        console.log(1);
      } else {
        const filePath = Path.join(dir, fileDirs[i]);
        m++;
        const dirName = Path.dirname(filePath);
        const fileName = Path.basename(dirName);

        const response = await readParame(dirMap[fileName], filePath);
        console.log('第' + m + '张', response?.data?.id);
      }
    } else {
      //获取各个分类目录名
      const tempDir = Path.join(dir, fileDirs[i]);
      const dirObj = await updateDir(fileDirs[i]);
      dirMap[fileDirs[i]] = dirObj;
      console.log(tempDir, dirMap);

      getFilesForAvatar(tempDir);
    }
  }
}
//  2创建属性分类
async function updateDir(dirName) {
  //缓存判断
  if (Object.keys(dirMap).includes(dirName)) {
    return dirMap[dirName];
  }
  const params = {
    name: dirName,
    description: '',
    parentId: '3',
  };
  var url = 'http://localhost:3009/api/templateCategory/addForName';
  const config = {
    headers: {
      'Content-Type': 'application/json',
      authorization: authorization,
    },
  };
  return new Promise((resolve) => {
    axios
      .post(url, params, config)
      .then(async function (response) {
        // console.log(response.data);
        resolve(response.data.data);
      })
      .catch(function (error) {
        console.log(error);
      });
  });
}
// 3 创建模板记录
async function readParame(dirObj, filePath) {
  const ext = Path.extname(filePath);
  const fileName = Path.basename(filePath);
  var name =
    fileName.length > 8
      ? fileName.replace(ext, '')
      : dirObj.name + fileName.replace(ext, '');
  name = name.length > 6 ? name.substring(0, 6) : name;

  const params = {
    categoryId: dirObj.id,
    title: name, //取文件名前4个字
    type: 'avatar',
  };

  var url = 'http://localhost:3009/api/template/addForName';
  const config = {
    headers: {
      'Content-Type': 'application/json',
      authorization: authorization,
    },
  };

  return new Promise((resolve) => {
    axios
      .post(url, params, config)
      .then(async function (response) {
        console.log(response.data);
        if (response.data.code == 0 && response.data.data) {
          setTimeout(
            async () => {
              const data = await uploadScript(filePath, response.data.data);
              resolve(data);
            },
            Math.random() * 200 + 100,
          );
        } else {
          resolve({ id: '跳过' + params.title });
        }
      })
      .catch(function (error) {
        console.log(error);
        resolve({ id: '跳过' + params.title });
      });
  });
}

// 4 上传文件
async function uploadScript(filePath, data) {
  var url = 'http://localhost:3009/api/file/uploadScript';

  const formData = new FormData();

  formData.append('file', fs.createReadStream(filePath));
  formData.append('categoryId', data.categoryId);
  formData.append('templateId', data.id);
  // formData.append('templateId', "e8849fe0-d9c0-4eb7-9661-aafc6745aff6");
  formData.append('name', new Date().getTime());
  const config = {
    headers: {
      'Content-Type': 'multipart/form-data;boundary=' + new Date().getTime(),
      authorization: authorization,
    },
  };
  const progressBar = new ProgressBar(
    `Uploading ${data.title} [:bar] :percent`,
    {
      total: fs.statSync(filePath).size,
      width: 40,
      complete: '=',
      incomplete: ' ',
    },
  );
  const response = await axios.post(url, formData, {
    headers: config.headers,
    onUploadProgress: (progressEvent) => {
      progressBar.tick(progressEvent.loaded);
    },
  });
  console.log(`Upload complete: ${response.data?.data?.id}`);
  return response?.data;
}
let dir = process.cwd();
console.log(dir); //是当前执行node命令的目录地址

console.log(dir); //
//挂件头像
// getFilesForAvatar('h:/1111pro/image-splider/result/avatar');
//表情包
// getFilesForAvatar('h:/1111pro/image-splider/gif/avatar');
getFilesForAvatar('/Users/a888/Downloads/tips/image-splider/result/avatar');

// getFilesForAvatar(dir+"/demo/img/avatar")

// deleteByToday
// async function deleteByToday() {
//   //缓存判断

//   const params = {};
//   var url = 'http://localhost:3009/api/file/deleteByToday';
//   const config = {
//     headers: {
//       'Content-Type': 'application/json',
//       authorization: authorization,
//     },
//   };
//   return new Promise((resolve) => {
//     axios
//       .post(url, params, config)
//       .then(async function (response) {
//         console.log("文件数据:",response.data.num);
//         resolve(response);
//       })
//       .catch(function (error) {
//         console.log(error);
//       });
//   });
// }

// deleteByToday()